package com.project.movie.controller.slice;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.project.movie.common.enums.BusinessType;
import com.project.movie.common.enums.ResultCode;
import com.project.movie.config.utils.ShiroUtils;
import com.project.movie.domain.*;
import com.project.movie.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author 超级管理员
 * @version 1.0
 * @description: 排片controller
 * @date 2025/02/07 09:46
 */
@Controller
@ResponseBody
@RequestMapping("slice")
public class MovieSliceController {

    @Autowired
    private MovieSliceService movieSliceService;
    @Autowired
    private MoviePriceService moviePriceService;
    @Autowired
    private MovieSeatService movieSeatService;
    @Autowired
    private MovieCinemaService movieCinemaService;
    @Autowired
    private MovieOfficeService movieOfficeService;
    @Autowired
    private MovieItemService movieItemService;

    /** 分页获取排片 */
    @PostMapping("getMovieSlicePage")
    public Result getMovieSlicePage(@RequestBody MovieSlice movieSlice) {
        Page<MovieSlice> page = new Page<>(movieSlice.getPageNumber(),movieSlice.getPageSize());
        QueryWrapper<MovieSlice> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(StringUtils.isNotBlank(movieSlice.getItemId()),MovieSlice::getItemId,movieSlice.getItemId())
                .eq(StringUtils.isNotBlank(movieSlice.getCinemaId()),MovieSlice::getCinemaId,movieSlice.getCinemaId())
                .eq(StringUtils.isNotBlank(movieSlice.getLanguage()),MovieSlice::getLanguage,movieSlice.getLanguage());
        Page<MovieSlice> movieSlicePage = movieSliceService.page(page, queryWrapper);
        for (MovieSlice slice : movieSlicePage.getRecords()) {
            MovieCinema cinema = movieCinemaService.getById(slice.getCinemaId());
            slice.setCinemaName(cinema.getName());
            MovieOffice office = movieOfficeService.getById(slice.getOfficeId());
            slice.setOfficeName(office.getName());
        }
        return Result.success(movieSlicePage);
    }

    @PostMapping("getMovieSlicePageByManager")
    public Result getMovieSlicePageByManager(@RequestBody MovieSlice movieSlice) {
        User userInfo = ShiroUtils.getUserInfo();
        QueryWrapper<MovieCinema> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(MovieCinema::getUserId,userInfo.getId());
        List<MovieCinema> cinemaList = movieCinemaService.list(wrapper);
        List<String> list = new ArrayList<>();
        for (MovieCinema movieCinema : cinemaList) {
            list.add(movieCinema.getId());
        }
        Page<MovieSlice> page = new Page<>(movieSlice.getPageNumber(),movieSlice.getPageSize());
        QueryWrapper<MovieSlice> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .in(list.size() > 0,MovieSlice::getCinemaId,list)
                .eq(StringUtils.isNotBlank(movieSlice.getItemId()),MovieSlice::getItemId,movieSlice.getItemId())
                .eq(StringUtils.isNotBlank(movieSlice.getLanguage()),MovieSlice::getLanguage,movieSlice.getLanguage());
        Page<MovieSlice> movieSlicePage = movieSliceService.page(page, queryWrapper);
        for (MovieSlice slice : movieSlicePage.getRecords()) {
            MovieCinema cinema = movieCinemaService.getById(slice.getCinemaId());
            slice.setCinemaName(cinema.getName());
            MovieOffice office = movieOfficeService.getById(slice.getOfficeId());
            slice.setOfficeName(office.getName());
            MovieItem movieItem = movieItemService.getById(slice.getItemId());
            slice.setItemName(movieItem.getName());
        }
        return Result.success(movieSlicePage);
    }

    @PostMapping("getMovieSliceList")
    public Result getMovieSliceList(@RequestBody MovieSlice movieSlice) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        QueryWrapper<MovieSlice> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(StringUtils.isNotBlank(movieSlice.getItemId()),MovieSlice::getItemId,movieSlice.getItemId())
                .eq(StringUtils.isNotBlank(movieSlice.getCinemaId()),MovieSlice::getCinemaId,movieSlice.getCinemaId())
                .eq(StringUtils.isNotBlank(movieSlice.getLanguage()),MovieSlice::getLanguage,movieSlice.getLanguage())
                .groupBy(MovieSlice::getLookDate);
        List<MovieSlice> movieSlicePage = movieSliceService.list(queryWrapper);
        List<MovieSlice> list = new ArrayList<>();
        for (MovieSlice slice : movieSlicePage) {
            String start = format.format(slice.getLookDate()) + " " + slice.getStart() + ":00";
            Date date = simpleDateFormat.parse(start);
            if (date.after(new Date())) {
                list.add(slice);
            }
        }
        return Result.success(list);
    }

    @PostMapping("getMovieSliceByDate")
    public Result getMovieSliceByDate(@RequestBody MovieSlice movieSlice) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String formatted = simpleDateFormat.format(movieSlice.getLookDate());
        QueryWrapper<MovieSlice> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(MovieSlice::getLookDate,formatted)
                .eq(StringUtils.isNotBlank(movieSlice.getItemId()),MovieSlice::getItemId,movieSlice.getItemId())
                .eq(StringUtils.isNotBlank(movieSlice.getCinemaId()),MovieSlice::getCinemaId,movieSlice.getCinemaId())
                .eq(StringUtils.isNotBlank(movieSlice.getLanguage()),MovieSlice::getLanguage,movieSlice.getLanguage());
        List<MovieSlice> movieSlicePage = movieSliceService.list(queryWrapper);
        for (MovieSlice slice : movieSlicePage) {
            MovieCinema cinema = movieCinemaService.getById(slice.getCinemaId());
            slice.setCinemaName(cinema.getName());
            MovieOffice office = movieOfficeService.getById(slice.getOfficeId());
            slice.setOfficeName(office.getName());
        }
        return Result.success(movieSlicePage);
    }

    /** 根据id获取排片 */
    @GetMapping("getMovieSliceById")
    public Result getMovieSliceById(@RequestParam("id")String id) {
        MovieSlice movieSlice = movieSliceService.getById(id);
        MovieCinema cinema = movieCinemaService.getById(movieSlice.getCinemaId());
        movieSlice.setCinemaName(cinema.getName());
        MovieOffice office = movieOfficeService.getById(movieSlice.getOfficeId());
        movieSlice.setOfficeName(office.getName());
        return Result.success(movieSlice);
    }

    /** 保存排片 */
    @PostMapping("saveMovieSlice")
    @Transactional(rollbackFor = Exception.class)
    public Result saveMovieSlice(@RequestBody MovieSlice movieSlice) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date lookDate = movieSlice.getLookDate();
        String formatted = simpleDateFormat.format(lookDate);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String start = formatted + " " + movieSlice.getStart() + ":00";
        String end = formatted + " " + movieSlice.getEnd() + ":59";
        Date startTime = dateFormat.parse(start);
        Date endTime = dateFormat.parse(end);
        movieSlice.setStartTime(startTime);
        movieSlice.setEndTime(endTime);
        String idStr = IdWorker.getIdStr();
        movieSlice.setId(idStr);
        //判断影院影厅有没有冲突
        QueryWrapper<MovieSlice> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(MovieSlice::getOfficeId,movieSlice.getOfficeId()).eq(MovieSlice::getLookDate,movieSlice.getLookDate())
                .and(w-> w.between(MovieSlice::getStartTime,startTime,endTime)
                        .or().between(MovieSlice::getEndTime,startTime,endTime));
        int countTime = movieSliceService.count(queryWrapper);
        if (countTime > 0) {
            return Result.fail("该影院影厅排片时间冲突");
        }
        boolean save = movieSliceService.save(movieSlice);
        QueryWrapper<MovieSeat> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(MovieSeat::getOfficeId,movieSlice.getOfficeId());
        List<MovieSeat> seatList = movieSeatService.list(wrapper);
        for (int i = 0; i < seatList.size(); i++) {
            MovieSeat movieSeat = seatList.get(i);
            for (int j = 0; j < movieSeat.getNum(); j++) {
                MoviePrice moviePrice1 = new MoviePrice();
                moviePrice1.setPrice(0);
                moviePrice1.setItemId(movieSlice.getItemId());
                moviePrice1.setOfficeId(movieSlice.getOfficeId());
                moviePrice1.setSliceId(movieSlice.getId());
                moviePrice1.setRowIndex(i);
                moviePrice1.setColumnIndex(j);
                moviePriceService.save(moviePrice1);
            }
        }
        if (save) {
            return Result.success();
        } else {
            return Result.fail(ResultCode.COMMON_DATA_OPTION_ERROR.getMessage());
        }
    }

    /** 编辑排片 */
    @PostMapping("editMovieSlice")
    @Transactional(rollbackFor = Exception.class)
    public Result editMovieSlice(@RequestBody MovieSlice movieSlice) throws ParseException {
        //查询有没有卖出去过
        QueryWrapper<MoviePrice> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(MoviePrice::getSliceId,movieSlice.getId())
                .eq(MoviePrice::getState,0);
        int count = moviePriceService.count(queryWrapper);
        if (count > 0) {
            return Result.fail("已有座位卖出，无法修改");
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date lookDate = movieSlice.getLookDate();
        String formatted = simpleDateFormat.format(lookDate);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String start = formatted + " " + movieSlice.getStart() + ":00";
        String end = formatted + " " + movieSlice.getEnd() + ":59";
        Date startTime = dateFormat.parse(start);
        Date endTime = dateFormat.parse(end);
        movieSlice.setStartTime(startTime);
        movieSlice.setEndTime(endTime);
        //判断影院影厅有没有冲突
        QueryWrapper<MovieSlice> wrapper = new QueryWrapper<>();
        wrapper.lambda().ne(MovieSlice::getId,movieSlice.getId()).eq(MovieSlice::getOfficeId,movieSlice.getOfficeId()).eq(MovieSlice::getLookDate,movieSlice.getLookDate())
                .and(w-> w.between(MovieSlice::getStartTime,startTime,endTime).or().between(MovieSlice::getEndTime,startTime,endTime));
        int countTime = movieSliceService.count(wrapper);
        if (countTime > 0) {
            return Result.fail("该影院影厅排片时间冲突");
        }
        boolean save = movieSliceService.updateById(movieSlice);
        if (save) {
            return Result.success();
        } else {
            return Result.fail(ResultCode.COMMON_DATA_OPTION_ERROR.getMessage());
        }
    }

    /** 删除排片 */
    @GetMapping("removeMovieSlice")
    public Result removeMovieSlice(@RequestParam("ids")String ids) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd");
        if (StringUtils.isNotBlank(ids)) {
            String[] asList = ids.split(",");
            for (String id : asList) {
                MovieSlice slice = movieSliceService.getById(id);
                String string = simple.format(slice.getLookDate()) + " " + slice.getEnd() + ":59";
                Date parse = simpleDateFormat.parse(string);
                if (new Date().before(parse)) {
                    //查询有没有卖出去过
                    QueryWrapper<MoviePrice> queryWrapper = new QueryWrapper<>();
                    queryWrapper.lambda()
                            .eq(MoviePrice::getSliceId,id)
                            .eq(MoviePrice::getState,0);
                    int count = moviePriceService.count(queryWrapper);
                    if (count > 0) {
                        return Result.fail("已有座位卖出，无法删除");
                    }
                }
                movieSliceService.removeById(id);
            }
            return Result.success();
        } else {
            return Result.fail("排片id不能为空！");
        }
    }

}
